// src/api.service.js
import axios from 'axios';
import { ElMessage } from 'element-plus'
// import { useRouter } from 'vue-router'
import router from './router/index'
// import { useStore } from 'vuex';
// import { inject, } from 'vue';
// var resetAcitve = inject('resetAcitve');

// resetAcitve()
const apiBaseUrl = (typeof import.meta !== 'undefined' && import.meta.env && import.meta.env.VITE_API_BASE_URL) || 'http://localhost:5226/api/';
const apiClient = axios.create({
    baseURL: apiBaseUrl, // 替换为你的API基础URL
    timeout: 10000,
    headers: { 'X-Custom-Header': 'foobar' } // 可以添加自定义请求头
});
apiClient.interceptors.request.use(function (config) {
    const savedUserInfo = JSON.parse( localStorage.getItem('userInfo'));
    // const store = useStore();
    console.log('savedUserInfo',savedUserInfo)
    if(savedUserInfo&&savedUserInfo.token){
        // 例如，添加认证令牌
        config.headers.Authorization = 'Bearer ' + savedUserInfo.token;
    }
    return config;
}, function (error) {
    // 对请求错误做些什么
    console.log('cc')
    return Promise.reject(error);
});

apiClient.interceptors.response.use(function (response) {
    // 对响应数据进行处理

    // 例如，根据响应状态码进行不同的处理
    if (response.status === 200) {
        if (response.data.Code == 200) {
            return response;
        }
        ElMessage.error(response.data.Message)
    } else {
        console.log('errrr', response)
        ElMessage.error(response.data.Message)
        // 可以根据需要处理不同的 HTTP 状态码
        return response;
    }
}, function (error) {
    console.log('errrr1 ', error)
    console.log('router ', router)
    console.log('router currentRoute ', router.currentRoute.value.path)
    if (error.response.status == 401) {
        //记录登录前页面
        localStorage.setItem('beforeLoginPath', router.currentRoute.value.path)
        ElMessage.error('登录过期，请重新登录')
        router.push("Login")
    } else {
        ElMessage.error(error.message)

    }

    // 根据需要决定是否返回错误对象
    return Promise.reject(error);
});


const get = (url, config) => apiClient.get(url, config).then(response => response.data);
// const post = (url, data) => apiClient.post(url, data).then(response => response.data);

const post = (url, data, config) => {
    return apiClient.post(url, data, config)
        .then(response => {
            if (response && response.data) {
                return response.data;
            } else {
                return response
            }
        });
};

const put = (url, data, config) => apiClient.put(url, data, config).then(r => r.data ?? r);
const del = (url, config) => apiClient.delete(url, config).then(r => r.data ?? r);

// const post = (url, data) => apiClient.post(url, data);
// 可以继续添加其他HTTP方法，如put, delete等

export default {
    get,
    post,
    put,
    delete: del,
    // ...其他方法
};